import { _decorator, Component, EventTouch, Graphics, instantiate, log, Node, Prefab, UITransform, v2, v3, Vec2 } from 'cc';
import { EventType } from './enumType';
import EventMgr from './EventManager';
import { Ball } from './ball';
const { ccclass, property } = _decorator;

@ccclass('TakeAim')
export class TakeAim extends Component {
    private arraw: Node = null;
    private graphics: Graphics = null;
    @property(Prefab) ball: Prefab | null = null;

    private shootDir: Vec2 = null;
    currentBall:Ball = null;

    start() {
        this.node.on(Node.EventType.TOUCH_MOVE,this.onTouchMove,this);
        this.node.on(Node.EventType.TOUCH_END,this.onTouchEND,this);
        this.node.on(Node.EventType.TOUCH_START,this.onTouchMove,this);
        EventMgr.Instance.on(EventType.play,this.onshow,this)
        this.graphics = this.node.getComponent(Graphics);
        this.arraw = this.node.getChildByName("arraw");
        this.node.active = false;
    }
    onDestroy() {
        this.node.off(Node.EventType.TOUCH_MOVE,this.onTouchMove,this);
        this.node.off(Node.EventType.TOUCH_END,this.onTouchEND,this);
        this.node.off(Node.EventType.TOUCH_START,this.onTouchMove,this);
        EventMgr.Instance.off(EventType.play,this.onshow)
    }
    shooter(){
        if(this.currentBall){
            this.currentBall.shooter(this.shootDir);
            this.currentBall = null;
            this.scheduleOnce(() => this.newBall(), 0.3);
        }
        
    }

    newBall(){
        if(this.ball){
            let ball = instantiate(this.ball);
            ball.setParent(this.node);
            this.currentBall = ball.getComponent(Ball);
            this.currentBall.init(Math.floor(Math.random() * 3));
        }
    }

    onshow(){
        this.node.active = true; 
        this.newBall();
    }
    
    onTouchEND(event: EventTouch){
        this.shooter();
        this.graphics.clear();
    }

    onTouchMove(event: EventTouch){
        let origin = this.arraw.getPosition();
        let touchPos = this.node.getComponent(UITransform).convertToNodeSpaceAR(v3(event.getUILocation().x,event.getUILocation().y,0));
        
        let dir = touchPos.subtract(origin);
        
        let length = 50;
        let lineLength = dir.length()*2;
        let increment = dir.normalize().multiplyScalar(length); //根据每条线段的长度获得一个增量向量
        let pos = origin.clone(); //临时变量

        pos.add(increment);
        this.graphics.clear();
        //只要线段长度还大于每条线段的长度
        while (lineLength >= length) {
            this.graphics.circle(pos.x, pos.y, 5);
            this.graphics.fill();
            pos.add(increment);
            lineLength -= length;
        }

        var angle = Math.atan2(dir.y, dir.x) / Math.PI * 180;
        this.arraw.angle = angle;
        this.shootDir = v2(dir.x,dir.y);
    }
}


